<?php

    require_once("xajax/xajax.inc.php");
    require_once("ajax_lib.inc.php");
    require_once("hla_lib.inc.php");

    if (!empty($_POST['kit_id']))
    {
        $current_kit_id = trim($_POST['kit_id']);
        SetCookieSet('kit_id', $current_kit_id);
    }

    if (!empty($_POST['lot_no']))
        SetCookieSet('lot_no', trim(preg_replace("/\s\/\s.*/", "", $_POST['lot_no'])));

    if (!empty($_POST['institution']) && trim($_POST['institution']) != '')
        SetCookieSet('institution', trim($_POST['institution']));

    if (!empty($_POST['img_rotate']))
        SetCookieSet('img_rotate', $_POST['img_rotate']);

    if (!empty($_POST['img_zoom']))
        SetCookieSet('img_zoom', $_POST['img_zoom']);

    $GlobalXajax = new xajax($_SERVER['SCRIPT_NAME']);

    function Ajax_RefreshLotList($current_kit_id)
    {
        $XajaxResp = new xajaxResponse();

        require_once('inc.php');

        $lot_list = $HLA_DBTool->ExecAssocRows(
                    "select lot_no, max(lot_expires) as lot_expires from hla_sample \n".
                    "where kit_id='$current_kit_id' \n".
                    "and lot_no <> '' \n".
                    "group by lot_no\n".
                    "order by lot_no\n");

        $script = '';
        $script .= "document.getElementById('lot_no').options.length=1;\n";

        foreach ($lot_list as $line)
        {
            $script .= "var objOption = new Option('".$line['lot_no']." / ".MI_KIT_LOT_EXPIRES." ".substr($line['lot_expires'], 0, 10)."');\n";
            $script .= "document.getElementById('lot_no').options.add(objOption);\n";
            if (!empty($_COOKIE['lot_no']) && $line['lot_no'] == $_COOKIE['lot_no'])
                $script .= "objOption.selected = true;\n";
        }

        $XajaxResp->addScript($script);

        return $XajaxResp;
    }

    function Ajax_GetPatientInfo($institution, $patient_id)
    {
        $XajaxResp = new xajaxResponse();

        if (empty($patient_id))
            return $XajaxResp;

        require_once('inc.php');

        if (!empty($institution))
            $patient = $HLA_DBTool->ExecAssocRows(
                        "select * from hla_patient \n".
                        "where institution = ? \n".
                        "and patient_id = ? \n",
                        array($institution, $patient_id));
        else
            $patient = $HLA_DBTool->ExecAssocRows(
                        "select * from hla_patient \n".
                        "where (institution='' or institution is null)\n".
                        "and patient_id = ? \n",
                        array($patient_id));

        $script = '';

        if (count($patient) > 0)
        {
            $patient = $patient[0];
            $script .= 'show_patient_exists("'.
                    $patient['rowguid'].'","'.
                    $patient['institution'].'","'.$patient['patient_id'].'","'.$patient['ethnic'].'","'.
                    $patient['first_name'].'","'.$patient['last_name'].'","'.
                    $patient['sex'].'","'.$patient['age'].'");';
        }
        else
        {
            $script .= 'show_patient_not_exists();';
        }

        $script .= 'PatientIDVerified = true;';

        $XajaxResp->addScript($script);

        return $XajaxResp;
    }

    $GlobalXajax->registerFunction("Ajax_RefreshLotList");
    $GlobalXajax->registerFunction("Ajax_GetPatientInfo");
    $GlobalXajax->processRequests();

    require_once('header.inc.php');

    $op = '';
    if (!empty($_POST['op']))
        $op = $_POST['op'];
    else if (!empty($_GET['op']))
        $op = $_GET['op'];

    function Action_display()
    {
        global $HLA_DBTool, $HLA_ThemeCtrl, $HLA_MenuTabs, $HLA_UserInfo, $GlobalXajax, $op;

        $HLA_DBTool->MaxCount = 200;

        $kit_id_list = $HLA_DBTool->ExecKeyValues("select kit_id, kit_desc from hla_kit \n".
                        "order by kit_id");

        $HLA_ThemeCtrl->Assign('kit_id_list', $kit_id_list);

        $HLA_ThemeCtrl->Assign('current_kit_id', $_GET['kit_id']);

        if (count($kit_id_list) <= 0)
        {
            if (isset($HLA_MenuTabs['/maintain.php']))
                $HLA_ThemeCtrl->Msg(MI_ERROR_KITS, '/maintain.php');
            else
                $HLA_ThemeCtrl->Msg(MI_ERROR_KITS);

            return;
        }

        if (!empty($_GET['lot_no']))
        {
            $_GET['lot_no'] = trim(preg_replace("/\s\/\s.*/", "", $_GET['lot_no']));
            $HLA_ThemeCtrl->Assign('lot_no', $_GET['lot_no']);
        }

        $institutions = $HLA_DBTool->ExecAssocRows(
                    "select institution from hla_patient \n".
                    "where institution <> '' \n".
                    "group by institution\n".
                    "order by institution\n");

        $institution_list = array();
        foreach ($institutions as $row)
            $institution_list[] = $row['institution'];

        $HLA_ThemeCtrl->Assign('institution_list', $institution_list);

        if (!empty($_GET['institution']))
            $HLA_ThemeCtrl->Assign('institution', $_GET['institution']);

        $HLA_ThemeCtrl->Assign('test_by_list', $HLA_DBTool->ExecAssocRows(
                    "select test_by from hla_sample \n".
                    "where test_by <> '' \n".
                    "group by test_by\n".
                    "order by test_by\n"));

        if (!empty($_GET['genotypes']))
            $HLA_ThemeCtrl->Assign('genotypes', $_GET['genotypes']);

        if (!empty($_GET['proc_status']))
            $HLA_ThemeCtrl->Assign('proc_status', $_GET['proc_status']);

        if (!empty($_GET['sample_id']))
            $HLA_ThemeCtrl->Assign('sample_id', $_GET['sample_id']);

        if (!empty($_GET['test_by']))
            $HLA_ThemeCtrl->Assign('test_by', $_GET['test_by']);
        else
            $HLA_ThemeCtrl->Assign('test_by', $HLA_UserInfo['user_name']);

        if (!empty($_GET['patient_id']))
            $HLA_ThemeCtrl->Assign('patient_id', $_GET['patient_id']);

        if (!empty($_GET['name']))
            $HLA_ThemeCtrl->Assign('name', $_GET['name']);

        $HLA_ThemeCtrl->Assign('xajax_scripts', $GlobalXajax->getJavascript('/xajax/xajax_js/', 'xajax.js'));

        if ($op == 'search')
        {
            $search_geno_keys = array();

            if (!empty($_GET['genotypes']))
            {
                foreach (preg_split("/\s/", strtoupper(trim($_GET['genotypes']))) as $genotype_part)
                {
                    $genoindexes = ParseGenotypes($genotype_part);

                    if (count($genoindexes) <= 0)
                    {
                        $HLA_ThemeCtrl->Msg('['.$genotype_part.'] '.MI_GENOTYPES_NOT_MATCH, false);
                        return;
                    }

                    $search_geno_keys = array_merge($search_geno_keys, $genoindexes);
                }

                $search_geno_keys = array_unique($search_geno_keys);
                asort($search_geno_keys);
            }

//////////////////// New Samples ////////////////////////////////////////////////////////////

            if (!empty($_GET['institution']) || !empty($_GET['patient_id']) || !empty($_GET['name']))
            {
                if (count($search_geno_keys) <= 0)
                    $search_sql = "select distinct hla_sample.sample_id, patient_id, first_name, last_name, iif(final='Y','"._YES."','"._NO."') as final, hla_sample.rowguid \n".
                            "from hla_sample, hla_patient \n".
                            "where 1=1 \n".
                            "and hla_sample.patient_rowguid = hla_patient.rowguid\n";
                else
                {
                    $search_sql = "select distinct hla_sample.sample_id, patient_id, first_name, last_name, iif(final='Y','"._YES."','"._NO."') as final, hla_sample.rowguid \n".
                            "from hla_sample, hla_patient \n".
                            "where 1=1 \n".
                            "and hla_sample.patient_rowguid = hla_patient.rowguid\n";

                    foreach ($search_geno_keys as $search_genoindex)
                        $search_sql .= "and hla_sample.sample_id in (\n".
                                       "  select sample_id from hla_sample_types_search\n".
                                       "  where genoindex like '".$search_genoindex."%')\n";
                }
            }
            else
            {
                if (count($search_geno_keys) <= 0)
                    $search_sql = "select distinct hla_sample.sample_id, patient_id, first_name, last_name, iif(final='Y','"._YES."','"._NO."') as final, hla_sample.rowguid \n".
                            "from hla_sample \n".
                            "left join hla_patient on hla_sample.patient_rowguid = hla_patient.rowguid\n".
                            "where 1=1 \n";
                else
                {
                    $search_sql = "select distinct hla_sample.sample_id, patient_id, first_name, last_name, iif(final='Y','"._YES."','"._NO."') as final, hla_sample.rowguid \n".
                            "from hla_sample \n".
                            "left join hla_patient on hla_sample.patient_rowguid = hla_patient.rowguid\n".
                            "where 1=1 \n";

                    foreach ($search_geno_keys as $search_genoindex)
                        $search_sql .= "and hla_sample.sample_id in (\n".
                                       "  select sample_id from hla_sample_types_search\n".
                                       "  where genoindex like '".$search_genoindex."%')\n";
                }
            }

            $sample_header = array(MI_SAMPLE_ID, MI_PATIENT_ID, MI_FIRST_NAME, MI_LAST_NAME, MI_FINAL, MI_FINAL_TYPES);

            if (!empty($_GET['kit_id']))
                $search_sql .= "and kit_id='".$_GET['kit_id']."'\n";
            if (!empty($_GET['sample_id']))
            {
                if (preg_match("/^.*\~.*$/", $_GET['sample_id']))
                {
                    $sample_id_array = preg_split("/\s*\~\s*/", $_GET['sample_id']);
                    if (trim($sample_id_array[0]) != '' && trim($sample_id_array[1]) != '')
                        $search_sql .= "and (sample_id >= '".$sample_id_array[0]."' and sample_id <= '".$sample_id_array[1]."') \n";
                    else if (trim($sample_id_array[0]) != '')
                        $search_sql .= "and (sample_id >= '".$sample_id_array[0]."') \n";
                    else if (trim($sample_id_array[1]) != '')
                        $search_sql .= "and (sample_id <= '".$sample_id_array[1]."') \n";
                }
                else if (preg_match("/^.*[\*\s]+.*$/", $_GET['sample_id']))
                    $search_sql .= "and sample_id like '".preg_replace("/[\*\s]+/", "%", $_GET['sample_id'])."'\n";
                else
                    $search_sql .= "and sample_id like '%".$_GET['sample_id']."%'\n";
            }
            if (!empty($_GET['lot_no']))
                $search_sql .= "and lot_no like '%".$_GET['lot_no']."%'\n";
            if (!empty($_GET['test_by']))
                $search_sql .= "and test_by like '%".$_GET['test_by']."%'\n";
            if (!empty($_GET['proc_status']) && $_GET['proc_status'] != 'ANY')
            {
                if ($_GET['proc_status'] == 'Y')
                    $search_sql .= "and final='Y'\n";
                else
                    $search_sql .= "and final<>'Y'\n";
            }
            if (!empty($_GET['institution']))
                $search_sql .= "and institution like '%".$_GET['institution']."%'\n";
            if (!empty($_GET['patient_id']))
                $search_sql .= "and patient_id like '%".$_GET['patient_id']."%'\n";
            if (!empty($_GET['name']))
                $search_sql .= "and (first_name+' '+last_name like '%".preg_replace("/\s+/", "%", $_GET['name'])."%')\n";

            $search_sql .= "order by hla_sample.sample_id\n";

            $sample_rows = $HLA_DBTool->ExecAssocRows($search_sql, false, $result_count);

            $search_ret_sample_max_count = $HLA_DBTool->ResultCount;

            foreach ($sample_rows as $key => $row)
                #if ($row['final'] == _YES)
                {
                    $sample_genotype_rows = $HLA_DBTool->ExecAssocRows("select hla_pattern.serology_id, genotype from hla_sample, hla_sample_types, hla_pattern\n".
                        "where hla_sample.sample_id = '".$row['sample_id']."'\n".
                        "and hla_sample_types.sample_id = hla_sample.sample_id\n".
                        "and hla_sample_types.selected = 'Y'\n".
                        "and hla_pattern.kit_id = hla_sample.kit_id\n".
                        "and hla_pattern.serology_id = hla_sample_types.serology_id\n".
                        "and hla_pattern.line_no in (cint(left(hla_sample_types.line_no1, 3)), cint(left(hla_sample_types.line_no2, 3)))");

                    $last_genotype_serology_id = '';
                    $sample_genotype = '';
                    foreach ($sample_genotype_rows as $grows)
                    {
                        if ($sample_genotype == '')
                            $sample_genotype = preg_replace("/(\w+\*\d{2})(.*)/", "$1", $grows['genotype']);
                        else
                        {
                            if ($grows['serology_id'] == $last_genotype_serology_id)
                                $sample_genotype .= '||'.preg_replace("/(\w+\*\d{2})(.*)/", "$1", $grows['genotype']);
                            else
                                $sample_genotype .= ' '.preg_replace("/(\w+\*\d{2})(.*)/", "$1", $grows['genotype']);
                        }
                        $last_genotype_serology_id = $grows['serology_id'];
                    }

                    $sample_rows[$key]['final_types'] = $sample_genotype;
                }
                #else
                #    $sample_rows[$key]['final_types'] = '&nbsp;';

            $HLA_ThemeCtrl->Assign('search_ret_sample',
                array(
                    'header'=>$sample_header,
                    'rows'=>$sample_rows,
                    'link'=>"op=detail&rowguid="
                    )
                );

            $HLA_ThemeCtrl->Assign('search_ret_sample_display_count', min($HLA_DBTool->MaxCount, $search_ret_sample_max_count));
            $HLA_ThemeCtrl->Assign('search_ret_sample_max_count', $search_ret_sample_max_count);

            $search_sample_list = array();
            foreach ($sample_rows as $row)
                $search_sample_list[] = $row['sample_id'];

            $_SESSION['HLA']['search_sample_list'] = $search_sample_list;

//////////////////// Old Samples ////////////////////////////////////////////////////////////

            if ($_GET['proc_status'] == 'Y' || $_GET['proc_status'] == 'ANY')
            {
                if (count($search_geno_keys) <= 0)
                    $search_sql = "select hla_old_sample.Sample_ID, First_Name, Last_Name, min(hla_old_sample.rowguid) as rowguid\n".
                            "from hla_old_sample \n".
                            "where 1=1 \n";
                else
                {
                    $search_sql = "select hla_old_sample.Sample_ID, First_Name, Last_Name, min(hla_old_sample.rowguid) as rowguid \n".
                            "from hla_old_sample \n".
                            "where 1=1 \n";

                    foreach ($search_geno_keys as $search_genoindex)
                        $search_sql .= "and hla_old_sample.sample_id in (\n".
                                       "  select sample_id from hla_old_sample_types_search\n".
                                       "  where genoindex like '".$search_genoindex."%')\n";
                }

                if (!empty($_GET['kit_id']))
                    $search_sql .= "and Kit_Name='".$_GET['kit_id']."'\n";
                if (!empty($_GET['sample_id']))
                {
                    if (preg_match("/^.*\~.*$/", $_GET['sample_id']))
                    {
                        $sample_id_array = preg_split("/\s*\~\s*/", $_GET['sample_id']);
                        if (trim($sample_id_array[0]) != '' && trim($sample_id_array[1]) != '')
                            $search_sql .= "and (Sample_ID >= '".$sample_id_array[0]."' and Sample_ID <= '".$sample_id_array[1]."') \n";
                        else if (trim($sample_id_array[0]) != '')
                            $search_sql .= "and (Sample_ID >= '".$sample_id_array[0]."') \n";
                        else if (trim($sample_id_array[1]) != '')
                            $search_sql .= "and (Sample_ID <= '".$sample_id_array[1]."') \n";
                    }
                    else if (preg_match("/^.*[\*\s]+.*$/", $_GET['sample_id']))
                        $search_sql .= "and Sample_ID like '".preg_replace("/[\*\s]+/", "%", $_GET['sample_id'])."'\n";
                    else
                        $search_sql .= "and Sample_ID like '%".$_GET['sample_id']."%'\n";
                }
                if (!empty($_GET['lot_no']))
                    $search_sql .= "and Kit_Lot_ID like '%".$_GET['lot_no']."%'\n";
                if (!empty($_GET['test_by']))
                    $search_sql .= "and Tested_By like '%".$_GET['test_by']."%'\n";
                if (!empty($_GET['institution']))
                    $search_sql .= "and Institution like '%".$_GET['institution']."%'\n";
                if (!empty($_GET['name']))
                    $search_sql .= "and (First_Name+' '+Last_Name like '%".preg_replace("/\s+/", "%", $_GET['name'])."%')\n";

                $search_sql .= "group by hla_old_sample.Sample_ID, Kit_Name, Kit_Lot_ID, Tested_By, Institution, First_Name, Last_Name\n";
                $search_sql .= "order by hla_old_sample.Sample_ID\n";

                $old_sample_rows = $HLA_DBTool->ExecAssocRows($search_sql);

                $old_sample_header = array(MI_SAMPLE_ID, MI_FIRST_NAME, MI_LAST_NAME, MI_FINAL_TYPES);

                $search_ret_old_sample_max_count = $HLA_DBTool->ResultCount;

                foreach ($old_sample_rows as $key => $row)
                {
                    $sample_genotype_rows = $HLA_DBTool->ExecAssocRows("select genoindex as genotype from hla_old_sample_types_search\n".
                        "where hla_old_sample_types_search.sample_id = '".$row['Sample_ID']."'\n");

                    $sample_genotype = array();
                    foreach ($sample_genotype_rows as $grows)
                        $sample_genotype[] = preg_replace("/(\w+\*\d{2})(.*)/", "$1", $grows['genotype']);

                    $sample_genotype = array_unique($sample_genotype);

                    $old_sample_rows[$key]['final_types'] = implode(' ', $sample_genotype);
                }

                if (count($old_sample_rows) > 0)
                    $HLA_ThemeCtrl->Assign('search_ret_old_sample',
                        array(
                            'header'=>$old_sample_header,
                            'rows'=>$old_sample_rows,
                            'link'=>"op=old_detail&rowguid="
                            )
                        );

                $HLA_ThemeCtrl->Assign('search_ret_old_sample_display_count', min($HLA_DBTool->MaxCount, $search_ret_old_sample_max_count));
                $HLA_ThemeCtrl->Assign('search_ret_old_sample_max_count', $search_ret_old_sample_max_count);
            }

            $search_old_sample_list = array();
            foreach ($old_sample_rows as $row)
                $search_old_sample_list[] = $row['Sample_ID'];

            $_SESSION['HLA']['search_old_sample_list'] = $search_old_sample_list;

            $_SESSION['HLA']['search_uri'] = $_SERVER['REQUEST_URI'];
        }
        else
        {
            $_SESSION['HLA']['search_sample_list'] = null;
            $_SESSION['HLA']['search_old_sample_list'] = null;
            $_SESSION['HLA']['search_uri'] = null;
        }

        $HLA_ThemeCtrl->Display('search');
    }

    function Action_detail()
    {
        global $HLA_DBTool, $HLA_ThemeCtrl, $HLA_MenuTabs, $HLA_UserInfo, $GlobalXajax;

        if (empty($_GET['rowguid']) && empty($_GET['sample_id']))
        {
            echo "<script>";
            echo "history.go(-1);";
            echo "</script>";
            exit;
        }

        if (empty($_GET['full_serotypes']) || $_GET['full_serotypes'] != 'Y')
            $speed_serotypes = true;
        else
            $speed_serotypes = false;

        if (!empty($_GET['rowguid']))
            $sample = $HLA_DBTool->ExecAssocRows(
                        "select * from hla_sample \n".
                        "where rowguid = ".$_GET['rowguid']." \n");
        else
            $sample = $HLA_DBTool->ExecAssocRows(
                        "select * from hla_sample \n".
                        "where sample_id = '".$_GET['sample_id']."' \n");

        if (count($sample) > 0)
        {
            $sample = $sample[0];

            if (!empty($sample['patient_rowguid']))
            {
                $patient = $HLA_DBTool->ExecAssocRows(
                            "select * from hla_patient \n".
                            "where rowguid = ".intval($sample['patient_rowguid']));
                if (count($patient) > 0)
                    $patient = $patient[0];
                else
                {
                    unset($patient);
                    $sample['patient_rowguid'] = null;
                }
            }
        }
        else
        {
            echo "<script>";
            echo "history.go(-1);";
            echo "</script>";
            exit;
        }

        $sample_id = $sample['sample_id'];

        $kit = $HLA_DBTool->ExecAssocRows(
                    "select * from hla_kit \n".
                    "where kit_id = '".$sample['kit_id']."'");
        if (count($kit) == 0)
        {
            if (isset($HLA_MenuTabs['/maintain.php']))
                $HLA_ThemeCtrl->Msg(MI_ERROR_KITS, '/maintain.php');
            else
                $HLA_ThemeCtrl->Msg(MI_ERROR_KITS);

            return;
        }

        $HLA_ThemeCtrl->Assign('sample_id', $sample['sample_id']);
        $HLA_ThemeCtrl->Assign('kit_id', $sample['kit_id']);
        $HLA_ThemeCtrl->Assign('dna_ext_method', $sample['dna_ext_method']);
        $HLA_ThemeCtrl->Assign('dna_od', $sample['dna_od']);
        $HLA_ThemeCtrl->Assign('lot_no', $sample['lot_no']);
        $HLA_ThemeCtrl->Assign('lot_expires', $sample['lot_expires']);
        $HLA_ThemeCtrl->Assign('test_by', $sample['test_by']);
        $HLA_ThemeCtrl->Assign('test_date', $sample['test_date']);
        $HLA_ThemeCtrl->Assign('comment', $sample['comment']);
        $HLA_ThemeCtrl->Assign('final', $sample['final']);

        if ($sample['test_by'] == $HLA_UserInfo['user_name'] && $sample['final'] != 'Y')
            $HLA_ThemeCtrl->Assign('can_edit', true);
        else
            $HLA_ThemeCtrl->Assign('can_edit', false);

        if (!empty($sample['image_file_name']))
        {
            $i = 1;
            $sample_images = array();
            foreach (explode(",", $sample['image_file_name']) as $img_file)
                if (is_file(WEB_SAMPLE_IMAGES_PATH."/".$img_file))
                    $sample_images[] =
                        array(
                            "id"=>'sample_image'.($i++),
                            "src"=>"/sample_images/".$img_file
                            );
            $HLA_ThemeCtrl->Assign('sample_images', $sample_images);

            if (!empty($_COOKIE['img_rotate']))
                $HLA_ThemeCtrl->Assign('img_rotate', $_COOKIE['img_rotate']);

            if (!empty($_COOKIE['img_zoom']))
                $HLA_ThemeCtrl->Assign('img_zoom', $_COOKIE['img_zoom']);
        }

        if (!empty($patient))
        {
            $HLA_ThemeCtrl->Assign('patient_rowguid', $patient['rowguid']);
            $HLA_ThemeCtrl->Assign('institution', $patient['institution']);
            $HLA_ThemeCtrl->Assign('patient_id', $patient['patient_id']);
            $HLA_ThemeCtrl->Assign('ethnic', $patient['ethnic']);
            $HLA_ThemeCtrl->Assign('first_name', $patient['first_name']);
            $HLA_ThemeCtrl->Assign('last_name', $patient['last_name']);
            $HLA_ThemeCtrl->Assign('sex', $patient['sex']);
            if (!empty($patient['age']))
                $HLA_ThemeCtrl->Assign('age', $patient['age']);
        }
        else
        {
            $HLA_ThemeCtrl->Assign('patient_rowguid', false);
            if (!empty($_COOKIE['institution']))
                $HLA_ThemeCtrl->Assign('institution', $_COOKIE['institution']);
        }

        $lot_list = $HLA_DBTool->ExecAssocRows(
                    "select lot_no, max(lot_expires) as lot_expires from hla_sample \n".
                    "where kit_id='".$sample['kit_id']."' \n".
                    "and lot_no <> '' \n".
                    "group by lot_no\n".
                    "order by lot_no\n");

        foreach ($lot_list as $key => $line)
            $lot_list[$key]['lot_expires'] = substr($line['lot_expires'], 0, 10);

        $HLA_ThemeCtrl->Assign('lot_list', $lot_list);

        $sample_types = $HLA_DBTool->ExecAssocRows(
                    "select * from hla_sample_types \n".
                    "where sample_id='".$sample['sample_id']."' \n".
                    ($speed_serotypes?($sample['final']=='Y'?"and selected='Y'\n":"and (selected='Y' or imperfect<>'Y' or frequency>0)\n"):"").
                    "order by serology_id, selected desc, imperfect, frequency desc\n");

        $serotype_list = array();
        $serotype_rs = $HLA_DBTool->Execute(
                    "select serology_id, line_no, serotype, genotype from hla_pattern \n".
                    "where kit_id='".$sample['kit_id']."' \n".
                    "order by serology_id, line_no \n");
        while (!$serotype_rs->EOF)
        {
            $serotype_list[$serotype_rs->fields[0]][$serotype_rs->fields[1]]['serotype'] = $serotype_rs->fields[2];
            $serotype_list[$serotype_rs->fields[0]][$serotype_rs->fields[1]]['genotype'] = $serotype_rs->fields[3];
            $serotype_rs->MoveNext();
        }
        $serotype_rs->Close();


        $pno = 0;
        $last_serology_id = '';
        $has_rare = false;
        $matchs = array();
        foreach ($sample_types as $types)
        {
            if ($types['imperfect'] == 'N' && $types['frequency'] <= 0)
                $has_rare = true;

            if ($last_serology_id != $types['serology_id'])
            {
                switch ($view_color)
                {
                    case '#f5f5f5': $view_color = '#dbdbdb';    break;
                    case '#dbdbdb': $view_color = '#f5f5f5';    break;
                    default:        $view_color = '#f5f5f5';    break;
                }
                $last_serology_id = $types['serology_id'];
            }

            $sample_primer_numbers = explode(",", $sample['primer_numbers']);
            $match_numbers = array();
            foreach (explode(",", $types['primer_numbers']) as $match_number)
            {
                if (!in_array($match_number, $sample_primer_numbers))
                    $match_number = "<font color=red>".intval($match_number)."</font>";
                else
                    $match_number = intval($match_number);
                $match_numbers[] = $match_number;
            }
            $match_numbers = implode(",", $match_numbers);

            $serotype_list2 = $HLA_DBTool->ExecAssocRows(
                        "select serotype, genotype from hla_pattern \n".
                        "where kit_id='".$sample['kit_id']."' \n".
                        "and serology_id='".$types['serology_id']."' \n".
                        "and line_no in (".$types['line_no2'].") \n");

            $serotype1 = '';
            $serotype2 = '';
            $genotypes = '';
            $genotype1 = '';
            $genotype2 = '';

            foreach (explode(",", $types['line_no1']) as $line_no)
            {
                if ($serotype1 == '')
                    $serotype1 = $serotype_list[$types['serology_id']][intval($line_no)]['serotype'];
                else
                    $serotype1 .= '/'.$serotype_list[$types['serology_id']][intval($line_no)]['serotype'];
                if ($genotype1 == '')
                    $genotype1 = $serotype_list[$types['serology_id']][intval($line_no)]['genotype'];
                else
                    $genotype1 .= ' / '.$serotype_list[$types['serology_id']][intval($line_no)]['genotype'];
            }

            foreach (explode(",", $types['line_no2']) as $line_no)
            {
                if ($serotype2 == '')
                    $serotype2 = $serotype_list[$types['serology_id']][intval($line_no)]['serotype'];
                else
                    $serotype2 .= '/'.$serotype_list[$types['serology_id']][intval($line_no)]['serotype'];
                if ($genotype2 == '')
                    $genotype2 = $serotype_list[$types['serology_id']][intval($line_no)]['genotype'];
                else
                    $genotype2 .= ' / '.$serotype_list[$types['serology_id']][intval($line_no)]['genotype'];
            }

            $genotypes = $genotype1.' || '.$genotype2;

            $matchs[$types['serology_id']][] =
                array(
                    'view_color' => $view_color,
                    'serology_id' => $types['serology_id'],
                    'serotype1' => $serotype1,
                    'serotype2' => $serotype2,
                    'genotypes' => $genotypes,
                    'line_no1' => $types['line_no1'],
                    'line_no2' => $types['line_no2'],
                    'match_numbers' => $match_numbers,
                    'match_save_primer_numbers' => $types['primer_numbers'],
                    'frequency' => $types['frequency'],
                    'imperfect' => $types['imperfect'],
                    'rare' => ($types['imperfect']=='Y'?'N':($types['frequency']<=0?'Y':'N')),
                    'pno' => $pno,
                    'selected' => $types['selected'],
                );

            $pno++;
        }

        $serology_list = $HLA_DBTool->ExecAssocRows(
                    "select serology_id,serology_desc from hla_serology \n".
                    "where kit_id = ? \n".
                    "order by serology_id",
                    array($sample['kit_id']));

        $serology_match_info = array();
        foreach ($serology_list as $serology)
        {
            $imperfect_count = 0;
            $rare_count = 0;
            $match_count = 0;

            if (isset($matchs[$serology['serology_id']]))
            {
                foreach ($matchs[$serology['serology_id']] as $match)
                    if ($match['imperfect'] == 'Y')
                        $imperfect_count++;
                    else if ($match['rare'] == 'Y')
                        $rare_count++;
                    else
                        $match_count++;
            }

            $serology_match_info[$serology['serology_id']] = array(
                'match_count'=>$match_count,
                'imperfect_count'=>$imperfect_count,
                'rare_count'=>$rare_count
                );
        }

        $display_primer_numbers = $sample['primer_numbers'];
        $display_primer_numbers = preg_replace("/^0+/", "", $display_primer_numbers);
        $display_primer_numbers = preg_replace("/\,0+/", ",", $display_primer_numbers);

        $HLA_ThemeCtrl->Assign('display_primer_numbers', $display_primer_numbers);
        $HLA_ThemeCtrl->Assign('serology_match_info', $serology_match_info);
        $HLA_ThemeCtrl->Assign('matchs', $matchs);
        $HLA_ThemeCtrl->Assign('matchs_max_pno', $pno);
        $HLA_ThemeCtrl->Assign('has_rare', $has_rare);
        $HLA_ThemeCtrl->Assign('speed_serotypes', $speed_serotypes);

        $HLA_ThemeCtrl->Assign('xajax_scripts', $GlobalXajax->getJavascript('/xajax/xajax_js/', 'xajax.js'));

        if (!empty($_SESSION['HLA']['search_sample_list']))
        {
            $search_sample_list = $_SESSION['HLA']['search_sample_list'];
            $data_idx = array_search($sample_id, $search_sample_list);
            if ($data_idx !== false)
            {
                if (isset($search_sample_list[$data_idx-1]))
                    $HLA_ThemeCtrl->Assign('prior_sample_id', $search_sample_list[$data_idx-1]);
                if (isset($search_sample_list[$data_idx+1]))
                    $HLA_ThemeCtrl->Assign('next_sample_id', $search_sample_list[$data_idx+1]);
            }
        }

        if (!empty($_SESSION['HLA']['search_uri']))
            $HLA_ThemeCtrl->Assign('search_uri', $_SESSION['HLA']['search_uri']);

        $HLA_ThemeCtrl->Display('search_detail');
    }

    function Action_old_detail()
    {
        global $HLA_DBTool, $HLA_ThemeCtrl, $HLA_MenuTabs;

        if (empty($_GET['rowguid']) && empty($_GET['sample_id']))
        {
            echo "<script>";
            echo "history.go(-1);";
            echo "</script>";
            exit;
        }

        if (!empty($_GET['rowguid']))
            $sample = $HLA_DBTool->ExecAssocRows(
                        "select * from hla_old_sample \n".
                        "where rowguid = ".$_GET['rowguid']." \n");
        else
            $sample = $HLA_DBTool->ExecAssocRows(
                        "select * from hla_old_sample \n".
                        "where sample_id = '".$_GET['sample_id']."' \n");

        if (count($sample) > 0)
            $sample = $sample[0];
        else
        {
            echo "<script>";
            echo "history.go(-1);";
            echo "</script>";
            exit;
        }

        $sample_id = $sample['Sample_ID'];

        $HLA_ThemeCtrl->Assign('sample_id', $sample['Sample_ID']);
        $HLA_ThemeCtrl->Assign('kit_id', $sample['Kit_Name']);
        $HLA_ThemeCtrl->Assign('dna_ext_method', $sample['dna_ext_method']);
        $HLA_ThemeCtrl->Assign('dna_od', $sample['DNA_OD']);
        $HLA_ThemeCtrl->Assign('lot_no', $sample['Kit_Lot_ID']);
        $HLA_ThemeCtrl->Assign('lot_expires', $sample['Kit_Expires']);
        $HLA_ThemeCtrl->Assign('test_by', $sample['Tested_By']);
        $HLA_ThemeCtrl->Assign('test_date', $sample['Test_Date']);
        $HLA_ThemeCtrl->Assign('comment', $sample['Comment']);

        $HLA_ThemeCtrl->Assign('institution', $sample['Institution']);
        $HLA_ThemeCtrl->Assign('ethnic', $sample['Ethnic']);
        $HLA_ThemeCtrl->Assign('first_name', $sample['First_Name']);
        $HLA_ThemeCtrl->Assign('last_name', $sample['Last_Name']);
        $HLA_ThemeCtrl->Assign('sex', $sample['Sex']);
        if (!empty($sample['Age']))
            $HLA_ThemeCtrl->Assign('age', $sample['Age']);

        $sample_types = $HLA_DBTool->ExecAssocRows(
                    "select Type, Type1, Type2, Combine_Alleles, primer_numbers from hla_old_sample \n".
                    "where Sample_ID='".$sample_id."' \n".
                    "order by Type, Type1, Type2\n");

        $display_primer_numbers = '';
        $serology_match_info = array();
        $pno = 0;
        $last_serology_id = '';
        $has_rare = false;
        $matchs = array();
        foreach ($sample_types as $types)
        {
            if ($last_serology_id != $types['Type'])
            {
                switch ($view_color)
                {
                    case '#f5f5f5': $view_color = '#dbdbdb';    break;
                    case '#dbdbdb': $view_color = '#f5f5f5';    break;
                    default:        $view_color = '#f5f5f5';    break;
                }
                $last_serology_id = $types['Type'];
            }

            $match_numbers = preg_replace("/,0+/", ",", preg_replace("/^0+/", "", $types['primer_numbers']));

            $matchs[$types['Type']][] =
                array(
                    'view_color' => $view_color,
                    'serology_id' => $types['Type'],
                    'serotype1' => $types['Type1'],
                    'serotype2' => $types['Type2'],
                    'genotypes' => $types['Combine_Alleles'],
                    'match_numbers' => $match_numbers,
                    'pno' => $pno,
                );

            if ($display_primer_numbers == '')
                $display_primer_numbers = $match_numbers;
            else
                $display_primer_numbers .= ' / '.$match_numbers;

            if (!isset($serology_match_info[$serology['Type']]['match_count']))
                $serology_match_info[$serology['Type']]['match_count'] = 1;
            else
                $serology_match_info[$serology['Type']]['match_count']++;

            $pno++;
        }

        $HLA_ThemeCtrl->Assign('display_primer_numbers', $display_primer_numbers);
        $HLA_ThemeCtrl->Assign('serology_match_info', $serology_match_info);
        $HLA_ThemeCtrl->Assign('matchs', $matchs);
        $HLA_ThemeCtrl->Assign('matchs_max_pno', $pno);

        if (!empty($_SESSION['HLA']['search_old_sample_list']))
        {
            $search_old_sample_list = $_SESSION['HLA']['search_old_sample_list'];
            $data_idx = array_search($sample_id, $search_old_sample_list);
            if ($data_idx !== false)
            {
                if (isset($search_old_sample_list[$data_idx-1]))
                    $HLA_ThemeCtrl->Assign('prior_sample_id', $search_old_sample_list[$data_idx-1]);
                if (isset($search_old_sample_list[$data_idx+1]))
                    $HLA_ThemeCtrl->Assign('next_sample_id', $search_old_sample_list[$data_idx+1]);
            }
        }

        if (!empty($_SESSION['HLA']['search_uri']))
            $HLA_ThemeCtrl->Assign('search_uri', $_SESSION['HLA']['search_uri']);

        $HLA_ThemeCtrl->Display('search_old_detail');
    }

    function Action_detail_save()
    {
        global $HLA_DBTool, $HLA_ThemeCtrl, $HLA_UserInfo;

        $sample_id = strtoupper($_POST['sample_id']);
        $current_kit_id = $_POST['kit_id'];

        if (empty($sample_id))
        {
            $HLA_ThemeCtrl->Msg(MI_ERROR_REQUIRE_SAMPLE_ID, false);
            return;
        }

        $sample = $HLA_DBTool->ExecAssocRows(
            "select * from hla_sample \n".
            "where sample_id = ? \n",
            array($sample_id));

        if (count($sample) == 0)
        {
            $HLA_ThemeCtrl->Msg(MI_SAMPLE_NOT_EXISTS_CANNOT_MODIFY, false);
            return;
        }

        $sample = $sample[0];

        if ($sample['final'] == 'Y')
        {
            $HLA_ThemeCtrl->Msg(MI_ERROR_SAMPLE_FINAL, false);
            return;
        }

        $current_kit_id = $sample['kit_id'];

        $sample_rowguid = $sample['rowguid'];

        if (
            $_POST['patient_rowguid'] != 'false' ||
            !empty($_POST['patient_id']) || !empty($_POST['ethnic']) ||
            !empty($_POST['first_name']) || !empty($_POST['last_name']) ||
            !empty($_POST['sex']) || !empty($_POST['age'])
            )
        {
            if (empty($_POST['institution']) || empty($_POST['patient_id']) ||
                empty($_POST['first_name']) || empty($_POST['last_name']))
            {
                $HLA_ThemeCtrl->Msg(MI_ERROR_REQUIRE_PATIENT_INFO, false);
                return;
            }
        }

        $final = !empty($_POST['final']) && $_POST['final'] == 'true';

        if ($final)
        {
            $check_field = array();
            for ($i=0; isset($_POST['line'.$i.'_serology_id']); $i++)
                if (!empty($_POST['line'.$i.'_checked']) && $_POST['line'.$i.'_checked'] == 'true')
                {
                    if (!isset($check_field[$_POST['line'.$i.'_serology_id']]))
                        $check_field[$_POST['line'.$i.'_serology_id']] = 1;
                    else
                        $check_field[$_POST['line'.$i.'_serology_id']]++;
                }

            $serologys = $HLA_DBTool->ExecAssocRows(
                            "select serology_id from hla_serology \n".
                            "where kit_id = '$current_kit_id' \n");

            foreach ($serologys as $row)
            {
                if (!isset($check_field[$row['serology_id']]) ||
                    $check_field[$row['serology_id']] > 1)
                {
                    $HLA_ThemeCtrl->Msg(MI_ERROR_REQUIRE_ONE_SEROLOGY, false);
                    return;
                }
            }
        }

        $patient_rowguid = '';

        if ($_POST['patient_rowguid'] != 'false')
        {
            $patient_rowguid = $HLA_DBTool->ExecOneField(
                            "select rowguid from hla_patient \n".
                            "where rowguid = ".intval($_POST['patient_rowguid'])." \n");

            if ($patient_rowguid === '')
            {
                $HLA_ThemeCtrl->Msg(MI_PATIENT_NOT_EXISTS, false);
                return;
            }

            $HLA_DBTool->Execute(
                "update hla_patient set \n".
                "ethnic = ?, ".
                "first_name = ? ,".
                "last_name = ? ,".
                "sex = ? ,".
                "age = ? \n".
                "where rowguid = ".intval($_POST['patient_rowguid'])." \n",
                array(
                    $_POST['ethnic'], $_POST['first_name'],
                    $_POST['last_name'], $_POST['sex'], intval($_POST['age'])
                    )
                );
        }
        else if (
                !empty($_POST['patient_id']) || !empty($_POST['ethnic']) ||
                !empty($_POST['first_name']) || !empty($_POST['last_name']) ||
                !empty($_POST['sex']) || !empty($_POST['age'])
                )
        {
            $HLA_DBTool->Execute(
                "insert into hla_patient \n".
                "(institution,patient_id,ethnic,first_name,last_name,sex,age)\n".
                "values(?, ?, ?, ?, ?, ?, ?)",
                array(
                    $_POST['institution'], $_POST['patient_id'], $_POST['ethnic'], $_POST['first_name'],
                    $_POST['last_name'], $_POST['sex'], intval($_POST['age'])
                    )
                );

            $patient_rowguid = $HLA_DBTool->ExecOneField(
                "select rowguid from hla_patient \n".
                "where first_name = ? \n".
                "and last_name = ? \n",
                array($_POST['first_name'], $_POST['last_name'])
                );
        }

        if ($patient_rowguid === '')
            $patient_rowguid = -1;

        if (!empty($_POST['lot_no']))
        {
            $lot_no = trim(preg_replace("/\s\/\s.*/", "", $_POST['lot_no']));
            $lot_expires = trim(preg_replace("/.*\/\s".MI_KIT_LOT_EXPIRES."\s/", "", $_POST['lot_no']));
        }
        else
        {
            $lot_no = '';
            $lot_expires = date('Y/m/d H:i:s');
        }

        $HLA_DBTool->Execute(
            "update hla_sample set\n".
            "patient_rowguid = ?, ".
            "dna_ext_method = ?, ".
            "dna_od = ?, ".
            "lot_no = ?, ".
            "lot_expires = ?, ".
            "comment = ?, ".
            "final = ? ".
            "where sample_id = ? ",
            array(
                $patient_rowguid,
                $_POST['dna_ext_method'], $_POST['dna_od'],
                $lot_no, $lot_expires,
                $_POST['comment'],
                'N',
                $sample_id
                )
            );

        for ($i=0; isset($_POST['line'.$i.'_serology_id']); $i++)
        {
            if (!empty($_POST['line'.$i.'_checked']) && $_POST['line'.$i.'_checked'] == 'true')
                $selected = 'Y';
            else
                $selected = 'N';

            $HLA_DBTool->Execute(
                "update hla_sample_types \n".
                "set selected = ? \n".
                "where sample_id = ? \n".
                "and serology_id = ? \n".
                "and line_no1 = ? \n".
                "and line_no2 = ? \n",
                array(
                    $selected,
                    $sample_id, $_POST['line'.$i.'_serology_id'],
                    $_POST['line'.$i.'_line_no1'], $_POST['line'.$i.'_line_no2'],
                    )
                );

            if ($final && $selected)
            {
                $HLA_DBTool->Execute(
                        "insert into hla_sample_types_search\n".
                        "(sample_id, genoindex)\n".
                        "select distinct '".$sample_id."', genoindex from hla_pattern_search\n".
                        "where serology_id = '".$_POST['line'.$i.'_serology_id']."'\n".
                        "and line_no in (".$_POST['line'.$i.'_line_no1'].",".$_POST['line'.$i.'_line_no2'].") \n".
                        "and not exists (select * from hla_sample_types_search\n".
                        "where hla_pattern_search.genoindex=hla_sample_types_search.genoindex\n".
                        "and sample_id = '".$sample_id."')"
                    );
            }
        }

        $buttons = array();

        if (!empty($_SESSION['HLA']['search_uri']))
            $buttons[MI_BACK_SEARCH] = $_SESSION['HLA']['search_uri'];

        if (!empty($_SESSION['HLA']['search_sample_list']))
        {
            $search_sample_list = $_SESSION['HLA']['search_sample_list'];
            $data_idx = array_search($sample_id, $search_sample_list);
            if ($data_idx !== false)
            {
                if (isset($search_sample_list[$data_idx+1]))
                    $buttons[MI_NEXT_SAMPLE] = $_SERVER['SCRIPT_NAME']."?op=detail&sample_id=".urlencode($search_sample_list[$data_idx+1]);
                else
                    $buttons[MI_NEXT_SAMPLE] = $_SERVER['SCRIPT_NAME']."?op=detail&sample_id=".urlencode($search_sample_list[0]);
            }
        }

        # if ($final)
        {
           # $HLA_DBTool->Execute(
           #    "update hla_sample set\n".
           #     "final = ? ".
           #     "where sample_id = ? ",
           #     array(
           #         'Y',
           #         $sample_id
           #         )
           #     );

            $buttons = array_merge(array(MI_PRINT=>"/sample_output.php?sample_id=".urlencode($sample_id)), $buttons);
        }

        $HLA_ThemeCtrl->Msg(MI_SAVE_SAMPLE_SUCCESS, $buttons);
    }

    function Action_detail_delete()
    {
        global $HLA_DBTool, $HLA_ThemeCtrl, $HLA_UserInfo;

        $sample_id = strtoupper($_POST['sample_id']);

        if (empty($sample_id))
        {
            $HLA_ThemeCtrl->Msg(MI_ERROR_REQUIRE_SAMPLE_ID, false);
            return;
        }

        $sample = $HLA_DBTool->ExecAssocRows(
            "select * from hla_sample \n".
            "where sample_id = ? \n",
            array($sample_id));

        if (count($sample) == 0)
        {
            $HLA_ThemeCtrl->Msg(MI_SAMPLE_NOT_EXISTS_CANNOT_DELETE, false);
            return;
        }

        $sample = $sample[0];

        if ($sample['final'] == 'Y')
        {
            $HLA_ThemeCtrl->Msg(MI_ERROR_SAMPLE_FINAL, false);
            return;
        }

        $HLA_DBTool->Execute(
                "delete from hla_sample_types_search \n".
                "where sample_id = '$sample_id' \n");
        $HLA_DBTool->Execute(
                "delete from hla_sample_types \n".
                "where sample_id = '$sample_id' \n");
        $HLA_DBTool->Execute(
                "delete from hla_sample \n".
                "where sample_id = '$sample_id' \n");

        $HLA_ThemeCtrl->Msg(MI_DELETE_SAMPLE_SUCCESS);
    }

    switch ($op)
    {
        case 'detail_save':

            Action_detail_save();

            break;

        case 'detail_delete':

            Action_detail_delete();

            break;

        case 'detail':

            Action_detail();

            break;

        case 'old_detail':

            Action_old_detail();

            break;

        default:

            Action_display();

            break;
    }

    require_once('footer.inc.php');

?>
